﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows.Forms;
using System.Xml;

namespace XimalayaAudioDownloader
{
    // Token: 0x02000003 RID: 3
    internal class CommonMethds
    {

        public static T StrToObj<T>(string str) where T : class
        {
            JavaScriptSerializer jsonSerialize = new JavaScriptSerializer();
            return jsonSerialize.Deserialize<T>(str);
        }

        /// <summary>
        /// 获取专辑信息
        /// </summary>
        /// <param name="albumId"></param>
        /// <param name="page"></param>
        /// <returns></returns>
        public static XmlyModel GetXMLYAlbumInfo(string albumId, int page = 1)
        {
            var url = $"https://www.ximalaya.com/revision/album/getTracksList?albumId={albumId}&pageNum={page}&sort=1";
            var html = GetHttpWebRequest(url);
            return StrToObj<XmlyModel>(html);
        }
        /// <summary>
        /// 获取专辑全部信息
        /// </summary>
        /// <param name="start"></param>
        /// <returns></returns>
        public static List<XmlyMusic> GetAllXMLY(XmlyModel start)
        {
            var list = new List<XmlyMusic>();
            list.AddRange(start.data.tracks);
            for (int i = 2; i < start.PageCount; i++)
            {
                list.AddRange(GetXMLYAlbumInfo(start.data.albumId, i).data.tracks);
            }
            return list;
        }

        public static void InitialDownloadList(DataGridView DownloadList)
        {
            DataGridViewCheckBoxColumn dataGridViewCheckBoxColumn = new DataGridViewCheckBoxColumn();
            dataGridViewCheckBoxColumn.HeaderText = "选择";
            dataGridViewCheckBoxColumn.Width = 40;
            DownloadList.Columns.Add(dataGridViewCheckBoxColumn);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn.HeaderText = "专辑编号";
            dataGridViewTextBoxColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn.Width = 80;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn2 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn2.HeaderText = "专辑名称";
            dataGridViewTextBoxColumn2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn2.Width = 100;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn2);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn3 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn3.HeaderText = "文件名称";
            dataGridViewTextBoxColumn3.Width = DownloadList.Width - 40 - 70 - 100 - 70 - 70 - 70 - 80;
            dataGridViewTextBoxColumn3.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn3);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn4 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn4.HeaderText = "下载地址";
            dataGridViewTextBoxColumn4.Width = 0;
            dataGridViewTextBoxColumn4.Visible = false;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn4);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn5 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn5.HeaderText = "时长";
            dataGridViewTextBoxColumn5.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn5.Width = 70;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn5);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn6 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn6.HeaderText = "文件大小";
            dataGridViewTextBoxColumn6.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn6.Width = 80;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn6);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn7 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn7.HeaderText = "平均速度";
            dataGridViewTextBoxColumn7.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn7.Width = 90;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn7);
            DataGridViewTextBoxColumn dataGridViewTextBoxColumn8 = new DataGridViewTextBoxColumn();
            dataGridViewTextBoxColumn8.HeaderText = "下载进度";
            dataGridViewTextBoxColumn8.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            dataGridViewTextBoxColumn8.Width = 80;
            DownloadList.Columns.Add(dataGridViewTextBoxColumn8);
        }

        // Token: 0x0600003F RID: 63 RVA: 0x000025D8 File Offset: 0x000007D8
        public static List<string> GetHtmlAttr(string html, string tag, string attr)
        {
            Regex regex = new Regex("(<" + tag + "[\\w\\W].+?>)");
            MatchCollection matchCollection = regex.Matches(html);
            List<string> list = new List<string>();
            Regex regex2 = new Regex("([a-zA-Z1-9_-]+)\\s*=\\s*(\\x27|\\x22)([^\\x27\\x22]*)(\\x27|\\x22)", RegexOptions.IgnoreCase);
            for (int i = 0; i < matchCollection.Count; i++)
            {
                MatchCollection matchCollection2 = regex2.Matches(matchCollection[i].ToString());
                for (int j = 0; j < matchCollection2.Count; j++)
                {
                    GroupCollection groups = matchCollection2[j].Groups;
                    bool flag = attr.ToUpper() == groups[1].Value.ToUpper();
                    if (flag)
                    {
                        list.Add(groups[3].Value);
                        break;
                    }
                }
            }
            return list;
        }

        // Token: 0x06000040 RID: 64 RVA: 0x000026C0 File Offset: 0x000008C0
        private static string GetWebClient(string url)
        {
            string result;
            try
            {
                WebClient webClient = new WebClient();
                Stream stream = webClient.OpenRead(url);
                StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                string text = streamReader.ReadToEnd();
                stream.Close();
                result = text;
            }
            catch
            {
                result = "网络状况不佳！";
            }
            return result;
        }

        // Token: 0x06000041 RID: 65 RVA: 0x00002724 File Offset: 0x00000924
        public static string GetHttpWebRequest(string url)
        {
            string result;
            try
            {
                Uri requestUri = new Uri(url);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
                httpWebRequest.UserAgent = "User-Agent:Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705";
                httpWebRequest.Accept = "*/*";
                httpWebRequest.KeepAlive = true;
                httpWebRequest.Headers.Add("Accept-Language", "zh-cn,en-us;q=0.5");
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                Stream responseStream = httpWebResponse.GetResponseStream();
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                string text = streamReader.ReadToEnd();
                streamReader.Close();
                responseStream.Close();
                httpWebResponse.Close();
                result = text;
            }
            catch
            {
                result = "网络状况不佳！";
            }
            return result;
        }

        // Token: 0x06000042 RID: 66 RVA: 0x000027E0 File Offset: 0x000009E0
        public static string GetSoundIDs(string url)
        {
            var htmlAttr = CommonMethds.GetHtmlAttr(CommonMethds.GetWebClient(url), "a", "href");
            var flag = htmlAttr.Count > 0;
            StringBuilder result = new StringBuilder();

            if (!flag)
            {
                return "当前网址不正确";
            }
            foreach (var item in htmlAttr)
            {
                var m = new Regex(@"yinyue/\d*/(\d*)").Match(item);
                if (m.Groups.Count >= 2)
                {
                    if (!string.IsNullOrEmpty(m.Groups[1].ToString()))
                    {
                        result.Append(m.Groups[1] + ",");
                    }
                }
            }
            return result.ToString().Trim(',');
        }

        // Token: 0x06000043 RID: 67 RVA: 0x00002824 File Offset: 0x00000A24
        public static CommonAudioInfo[] GetLizhiSounds(string tempUrl)
        {
            CommonAudioInfo[] result;
            try
            {
                string text = CommonMethds.GetHttpWebRequest(tempUrl);
                Regex regex = new Regex("(?m)<div class=\"box-title box-title-with-radio-controller\"[^>]*>(?<div>(?:\\w|\\W)*?)</div[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                Match match = regex.Match(text);
                text = text.Remove(0, match.Groups["div"].Index);
                regex = new Regex("(?m)<div class=\"recommendTitle clearfix fontYaHei\"[^>]*>(?<div>(?:\\w|\\W)*?)</div[^>]*>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
                match = regex.Match(text);
                text = text.Remove(match.Groups["div"].Index);
                List<string> htmlAttr = CommonMethds.GetHtmlAttr(text, "a", "data-duration");
                List<string> htmlAttr2 = CommonMethds.GetHtmlAttr(text, "a", "data-title");
                List<string> htmlAttr3 = CommonMethds.GetHtmlAttr(text, "a", "data-url");
                List<string> htmlAttr4 = CommonMethds.GetHtmlAttr(text, "a", "data-id");
                List<string> htmlAttr5 = CommonMethds.GetHtmlAttr(text, "a", "data-radio-name");
                CommonAudioInfo[] array = new CommonAudioInfo[htmlAttr3.Count];
                for (int i = 0; i < htmlAttr3.Count; i++)
                {
                    array[i] = new CommonAudioInfo();
                    array[i].Duration = int.Parse(htmlAttr[i]);
                    array[i].Title = htmlAttr2[i];
                    array[i].FilePath = htmlAttr3[i];
                    array[i].ID = htmlAttr4[i];
                    array[i].SirialName = htmlAttr5[i];
                }
                result = array;
            }
            catch
            {
                result = null;
            }
            return result;
        }

        // Token: 0x06000044 RID: 68 RVA: 0x000029BC File Offset: 0x00000BBC
        public static int SoundsCount(string sound_ids)
        {
            Regex regex = new Regex(",");
            MatchCollection matchCollection = regex.Matches(sound_ids);
            return matchCollection.Count;
        }

        // Token: 0x06000045 RID: 69 RVA: 0x000029E8 File Offset: 0x00000BE8
        public static string getSoundIDByIndex(string sound_ids, int index)
        {
            string text = string.Empty;
            int num = 0;
            for (int i = 0; i < sound_ids.Length; i++)
            {
                bool flag = sound_ids[i] == ',';
                if (flag)
                {
                    num++;
                }
                else
                {
                    bool flag2 = num == index - 1;
                    if (flag2)
                    {
                        text += sound_ids[i].ToString();
                    }
                    bool flag3 = num == index;
                    if (flag3)
                    {
                        break;
                    }
                }
            }
            return text;
        }


        public static string getQingtingSoundByIndex(string sound_ids, int index)
        {
            string text = string.Empty;
            int num = 0;
            for (int i = 0; i < sound_ids.Length; i++)
            {
                bool flag = sound_ids[i] == '}';
                if (flag)
                {
                    num++;
                }
                else
                {
                    bool flag2 = num == index - 1;
                    if (flag2)
                    {
                        text += sound_ids[i].ToString();
                    }
                    bool flag3 = num == index;
                    if (flag3)
                    {
                        break;
                    }
                }
            }
            return text;
        }

        // Token: 0x06000047 RID: 71 RVA: 0x00002AE0 File Offset: 0x00000CE0
        public static AudioInfo GetAudioInfo(string sound_id)
        {
            AudioInfo audioInfo = new AudioInfo();
            AudioInfo result;
            try
            {
                string address = "http://www.ximalaya.com/tracks/" + sound_id + ".json";
                WebClient webClient = new WebClient();
                Stream stream = webClient.OpenRead(address);
                StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding("utf-8"));
                string s = streamReader.ReadToEnd();
                stream.Close();
                MemoryStream stream2 = new MemoryStream(Encoding.Unicode.GetBytes(s));
                DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(AudioInfo));
                audioInfo = (AudioInfo)dataContractJsonSerializer.ReadObject(stream2);
                result = audioInfo;
            }
            catch
            {
                result = audioInfo;
            }
            return result;
        }

        // Token: 0x06000048 RID: 72 RVA: 0x00002B90 File Offset: 0x00000D90
        public static void DownloadFile(string URL, string filename, DataGridViewRow row, Label state)
        {
            System.Threading.Timer timer = new System.Threading.Timer(new TimerCallback(CommonMethds.SpeedTimer), null, 0, CommonMethds.SPD_INTERVAL_SEC * 1000);
            try
            {
                bool flag = File.Exists(filename);
                if (flag)
                {
                    File.Delete(filename);
                }
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
                httpWebRequest.Timeout = 10000;
                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                long contentLength = httpWebResponse.ContentLength;
                row.Cells[6].Value = ((float)contentLength / 1048576f).ToString("f2") + "MB";
                Stream responseStream = httpWebResponse.GetResponseStream();
                Stream stream = new FileStream(filename, FileMode.Create);
                long num = 0L;
                byte[] array = new byte[1024];
                int i = responseStream.Read(array, 0, array.Length);
                CommonMethds.totalTime = 1;
                while (i > 0)
                {
                    num = (long)i + num;
                    stream.Write(array, 0, i);
                    i = responseStream.Read(array, 0, array.Length);
                    Application.DoEvents();
                    row.Cells[8].Value = ((long)((int)num) / (contentLength / 100L)).ToString() + "%";
                    row.Cells[7].Value = ((double)num / 1024.0 / (double)CommonMethds.totalTime).ToString("f2") + "KB/S";
                    Application.DoEvents();
                }
                row.Cells[0].Value = false;
                row.Cells[8].Value = "100%";
                stream.Close();
                responseStream.Close();
                timer.Dispose();
            }
            catch (TimeoutException)
            {
                timer.Dispose();
                state.Text = "网络连接超时，请检查网络连接后重试！(Error3)";
            }
            catch (Exception)
            {
                timer.Dispose();
                state.Text = "网络连接超时，请检查网络连接后重试！(Error3)";
            }
        }

        // Token: 0x06000049 RID: 73 RVA: 0x00002DC8 File Offset: 0x00000FC8
        private static void SpeedTimer(object state)
        {
            CommonMethds.totalTime++;
        }

        // Token: 0x0600004A RID: 74 RVA: 0x00002DD8 File Offset: 0x00000FD8
        public static void DataGridView2Xml(DataGridView dgv, string xmlPath)
        {
            XmlDocument xmlDocument = new XmlDocument();
            XmlElement xmlElement = xmlDocument.CreateElement("DownloadList");
            xmlDocument.AppendChild(xmlElement);
            XmlNode xmlNode = xmlDocument.SelectSingleNode("DownloadList");
            foreach (DataGridViewRow dataGridViewRow in ((IEnumerable)dgv.Rows))
            {
                xmlElement = xmlDocument.CreateElement("UNIT");
                XmlElement xmlElement2 = xmlDocument.CreateElement("CHECKED");
                xmlElement2.InnerText = dataGridViewRow.Cells[0].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("SIRIALID");
                xmlElement2.InnerText = dataGridViewRow.Cells[1].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("SIRIALNAME");
                xmlElement2.InnerText = dataGridViewRow.Cells[2].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("FILENAME");
                xmlElement2.InnerText = dataGridViewRow.Cells[3].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("URL");
                xmlElement2.InnerText = dataGridViewRow.Cells[4].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("TIMELENGTH");
                xmlElement2.InnerText = dataGridViewRow.Cells[5].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("FILELENGTH");
                xmlElement2.InnerText = dataGridViewRow.Cells[6].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("SPEED");
                xmlElement2.InnerText = dataGridViewRow.Cells[7].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlElement2 = xmlDocument.CreateElement("PROGRESS");
                xmlElement2.InnerText = dataGridViewRow.Cells[8].Value.ToString();
                xmlElement.AppendChild(xmlElement2);
                xmlNode.AppendChild(xmlElement);
            }
            xmlDocument.Save(xmlPath);
            MessageBox.Show("保存下载列表成功！");
        }

        // Token: 0x0600004B RID: 75 RVA: 0x00003058 File Offset: 0x00001258
        public static void Xml2DataGridView(DataGridView dgv, TreeView SirialTree, string xmlPath)
        {
            try
            {
                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(xmlPath);
                XmlElement documentElement = xmlDocument.DocumentElement;
                dgv.Rows.Clear();
                foreach (XmlNode xmlNode in documentElement.ChildNodes)
                {
                    int index = dgv.Rows.Add();
                    dgv.Rows[index].Cells[0].Value = CommonMethds.string2bool(xmlNode["CHECKED"].InnerText);
                    dgv.Rows[index].Cells[1].Value = xmlNode["SIRIALID"].InnerText;
                    dgv.Rows[index].Cells[2].Value = xmlNode["SIRIALNAME"].InnerText;
                    dgv.Rows[index].Cells[3].Value = xmlNode["FILENAME"].InnerText;
                    dgv.Rows[index].Cells[4].Value = xmlNode["URL"].InnerText;
                    dgv.Rows[index].Cells[5].Value = xmlNode["TIMELENGTH"].InnerText;
                    dgv.Rows[index].Cells[6].Value = xmlNode["FILELENGTH"].InnerText;
                    dgv.Rows[index].Cells[7].Value = xmlNode["SPEED"].InnerText;
                    dgv.Rows[index].Cells[8].Value = xmlNode["PROGRESS"].InnerText;
                    bool flag = !CommonMethds.haveNodeInTreeView(SirialTree, xmlNode["SIRIALNAME"].InnerText);
                    if (flag)
                    {
                        TreeNode treeNode = SirialTree.Nodes["RootNode"];
                        TreeNode treeNode2 = new TreeNode(xmlNode["SIRIALNAME"].InnerText);
                        treeNode2.Checked = true;
                        treeNode.Nodes.Add(treeNode2);
                    }
                }
            }
            catch
            {
                MessageBox.Show("错误的列表文件，请重新选择！");
            }
        }

        // Token: 0x0600004C RID: 76 RVA: 0x00003328 File Offset: 0x00001528
        public static bool string2bool(string boolString)
        {
            bool flag = boolString.ToLower() == "false";
            bool result;
            if (flag)
            {
                result = false;
            }
            else
            {
                bool flag2 = boolString.ToLower() == "true";
                result = (!flag2 || true);
            }
            return result;
        }

        // Token: 0x0600004D RID: 77 RVA: 0x0000336C File Offset: 0x0000156C
        public static bool haveNodeInTreeView(TreeView tv, string nodeName)
        {
            bool result;
            for (int i = 0; i < tv.Nodes[0].Nodes.Count; i++)
            {
                bool flag = tv.Nodes[0].Nodes[i].Text == nodeName;
                if (flag)
                {
                    result = true;
                    return result;
                }
            }
            result = false;
            return result;
        }

        // Token: 0x0400001F RID: 31
        private static int totalTime = 0;

        // Token: 0x04000020 RID: 32
        private static int SPD_INTERVAL_SEC = 1;
    }
}
